package com.gomtel.las.theme1;

import java.util.Calendar;
import java.util.TimeZone;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * 日期的插件
 * @author luojunqing
 */
public class DateView extends View {

	private Calendar mCalendar;
	private boolean mAttached;

	public DateView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
		super(context, attrs, defStyleAttr, defStyleRes);
	}

	public DateView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	public DateView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public DateView(Context context) {
		super(context);
	}

	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(0xff000000);
		paint.setTextSize(60);
		int date = mCalendar.get(Calendar.DATE);
		int mouth = mCalendar.get(Calendar.MONTH);
		int x = getLeft() + getWidth() / 2;
		int y =  getTop() + getHeight() / 2;
		canvas.drawText(mouth + "/" + date, x, y, paint);
		canvas.save();
	}

	private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
				String tz = intent.getStringExtra("time-zone");
				mCalendar = Calendar.getInstance(TimeZone.getTimeZone(tz));
			} else {
				mCalendar = Calendar.getInstance(TimeZone.getDefault());
			}
			invalidate();
		}
	};

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		if (!mAttached) {
			mAttached = true;
			IntentFilter filter = new IntentFilter();
			filter.addAction(Intent.ACTION_TIME_TICK);
			filter.addAction(Intent.ACTION_TIME_CHANGED);
			filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
			filter.addAction("android.intent.action.USER_SWITCHED");

			getContext().registerReceiver(mIntentReceiver, filter, null, getHandler());
		}

		mCalendar = Calendar.getInstance(TimeZone.getDefault());
		invalidate();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		if (mAttached) {
			getContext().unregisterReceiver(mIntentReceiver);
			mAttached = false;
		}
	}
	

}
